package com.infisight.hudprojector.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiItemDetail;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.google.gson.Gson;
import com.infisight.hudprojector.R;
import com.infisight.hudprojector.adapter.ReTermAdapter;
import com.infisight.hudprojector.adapter.RoutePlanItemChooseAdapter;
import com.infisight.hudprojector.common.HudProjectApplication;
import com.infisight.hudprojector.data.AssociateKeyClass;
import com.infisight.hudprojector.data.SpeechVoiceData;
import com.infisight.hudprojector.data.StartNaviInfo;
import com.infisight.hudprojector.data.VoiceDataClass;
import com.infisight.hudprojector.kdxfspeech.SpeechVoiceCompound;
import com.infisight.hudprojector.kdxfspeech.SpeechVoiceRecognition;
import com.infisight.hudprojector.service.MusicService;
import com.infisight.hudprojector.util.CommonUtil;
import com.infisight.hudprojector.util.Constants;
import com.infisight.hudprojector.util.ToastUtil;
import com.infisight.hudprojector.util.WordDataSet;

/**
 * @author hao
 * 
 *         当可视范围改变时回调的接口OnCameraChangeListener
 */
@SuppressLint("ResourceAsColor")
public class GNaviFragment extends Fragment implements AMapNaviListener,
		OnGeocodeSearchListener {
	private String TAG = "GNaviFragment";
	private MapView mapView;
	private AMap aMap;
	RelativeLayout rl_gnavi;
	FrameLayout fl_gnavi;
	ListView associate_key;

	private String keyWord = "";// 要输入的poi搜索关键字
	private ProgressDialog progDialog = null;// 搜索时进度条
	List<AssociateKeyClass> lstAk47 = new ArrayList<AssociateKeyClass>();
	ReTermAdapter reTermAdapter;// 联想词
	RoutePlanItemChooseAdapter routePlanItemChooseAdapter;// 路径规划信息
	SpeechVoiceRecognition svr = null;
	private PoiResult poiResult; // poi返回的结果
	private PoiSearch.Query query;// Poi查询条件类
	private PoiSearch poiSearch;// POI搜索
	Gson gson;
	MarkerOptions mko;
	SpeechVoiceCompound svc;

	StartNaviInfo sni;
	NaviLatLng start_navi;
	NaviLatLng end_navi;
	String destination = null;
	boolean isOk = false;
	SharedPreferences sp;
	boolean isChooseRoutePlan = false;
	int height;
	String routePlanName = null;
	String pathAddress = null;
	String dis = null;
	String time = null;
	// 路径规划线路选择
	LinearLayout gnavi_ll_route_plans, gnavi_ll_not_traffic_plan,
			gnavi_ll_not_high_speed_plan, gnavi_ll_not_fees_plan = null;
	TextView gnavi_tv_not_traffic_plan,
			gnavi_tv_not_traffic_plan_distance_and_time = null;// 避免拥堵
	TextView gnavi_tv_not_high_speed_plan,
			gnavi_tv_not_high_speed_plan_distance_and_time = null;// 不走高速
	TextView gnavi_tv_not_fees_plan,
			gnavi_tv_not_fees_plan_distance_and_time = null;// 避免收费
	private RouteOverLay mRouteOverLay = null;
	private AMapNavi mAMapNavi = null;
	// 起点终点列表
	private ArrayList<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
	private ArrayList<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();

	GeocodeSearch geocoderSearch = null;
	RegeocodeQuery mRegeocodeQuery = null;

	// boolean isControlOper = false;
	public static GNaviFragment newInstance() {
		GNaviFragment fragment = new GNaviFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	@SuppressWarnings("deprecation")
	public GNaviFragment() {

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/*
		 * 设置离线地图存储目录，在下载离线地图或初始化地图设置; 使用过程中可自行设置, 若自行设置了离线地图存储的路径，
		 * 则需要在离线地图下载和使用地图页面都进行路径设置
		 */
		// Demo中为了其他界面可以使用下载的离线地图，使用默认位置存储，屏蔽了自定义设置
		// MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this);
		// mapView = (MapView)getActivity().findViewById(R.id.map);
		// mapView.onCreate(savedInstanceState);// 此方法必须重写
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mapView = (MapView) getActivity().findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		sp = getActivity().getSharedPreferences("bg_music_info", 0);
		initView();
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		return inflater.inflate(R.layout.gnavi_start, container, false);
	}

	// 初始化xml控件
	private void initView() {

		// 路线选择的容器
		gnavi_ll_route_plans = (LinearLayout) getActivity().findViewById(
				R.id.gnavi_ll_route_plans);
		// 避免拥堵的容器
		gnavi_ll_not_traffic_plan = (LinearLayout) getActivity().findViewById(
				R.id.gnavi_ll_not_traffic_plan);
		// 不走高速的容器
		gnavi_ll_not_high_speed_plan = (LinearLayout) getActivity()
				.findViewById(R.id.gnavi_ll_not_high_speed_plan);
		// 避免收费的容器
		gnavi_ll_not_fees_plan = (LinearLayout) getActivity().findViewById(
				R.id.gnavi_ll_not_fees_plan);
		// 避免拥堵
		gnavi_tv_not_traffic_plan = (TextView) getActivity().findViewById(
				R.id.gnavi_tv_not_traffic_plan);
		gnavi_tv_not_traffic_plan_distance_and_time = (TextView) getActivity()
				.findViewById(R.id.gnavi_tv_not_traffic_plan_distance_and_time);
		// 不走高速
		gnavi_tv_not_high_speed_plan = (TextView) getActivity().findViewById(
				R.id.gnavi_tv_not_high_speed_plan);
		gnavi_tv_not_high_speed_plan_distance_and_time = (TextView) getActivity()
				.findViewById(
						R.id.gnavi_tv_not_high_speed_plan_distance_and_time);
		// 避免收费
		gnavi_tv_not_fees_plan = (TextView) getActivity().findViewById(
				R.id.gnavi_tv_not_fees_plan);
		gnavi_tv_not_fees_plan_distance_and_time = (TextView) getActivity()
				.findViewById(R.id.gnavi_tv_not_fees_plan_distance_and_time);

		rl_gnavi = (RelativeLayout) getActivity().findViewById(R.id.rl_gnavi);// 左侧用户可操作提示
		fl_gnavi = (FrameLayout) getActivity().findViewById(R.id.fl_gnavi);// 地图和联想词容器
		associate_key = (ListView) getActivity().findViewById(
				R.id.associate_key);// 联想词
	}

	/**
	 * 初始化AMap对象
	 */
	@SuppressWarnings("deprecation")
	private void init() {
		mAMapNavi = AMapNavi.getInstance(getActivity());
		mAMapNavi.setAMapNaviListener(this);
		double a = 0.0;
		double b = 0.0;
		String lat = getActivity().getSharedPreferences(
				Constants.LOCATION_INFO, 0).getString(Constants.LATITUDE, "");
		String lon = getActivity().getSharedPreferences(
				Constants.LOCATION_INFO, 0).getString(Constants.LONGITUDE, "");
		if (lat != "" && lon != "") {
			a = Double.parseDouble(lat);
			b = Double.parseDouble(lon);
		}
		associate_key.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (isChooseRoutePlan) {
					sni = new StartNaviInfo(start_navi, end_navi, 0);
					svc.startSpeaking(Constants.F_C_WHAT_YOU_CHOOSE_ROUTE_PLAN
							+ reTermAdapter.lists.get(position)
							+ Constants.F_C_READY_NAVI);
					SpeechVoiceData data = new SpeechVoiceData();
					data.setCommand(Constants.MAIN_HUD_COM);
					data.setValue(gson.toJson(sni));
					CommonUtil.processBroadcast(getActivity(), data);
				} else {
					AssociateKeyClass akc = reTermAdapter.lists.get(position);
					// isControlOper = true;
					if (doSearchQuery(akc.getKeyName())) {
						// svc.startSpeaking(vdc.getPromptKey());

					}
				}
			}
		});
		if (aMap == null) {
			CameraUpdate mCameraUpdate = CameraUpdateFactory
					.changeLatLng(new LatLng(a, b));// 定义了一个可视区域
			aMap = mapView.getMap();
			// aMap.setMapType(3);//黑夜模式
			mko = new MarkerOptions();
			start_navi = new NaviLatLng(a, b);
			mko.icon(BitmapDescriptorFactory
					.fromResource(R.drawable.center_icon));
			mko.position(new LatLng(a, b));
			// mko.title("我的位置");
			// mko.visible(true);
			// mko.setFlat(false);
			aMap.addMarker(mko);
			aMap.animateCamera(mCameraUpdate);
			mko.perspective(true);
			aMap.setOnCameraChangeListener(new OnCameraChangeListener() {

				@Override
				public void onCameraChangeFinish(CameraPosition position) {
					// TODO Auto-generated method stub
					if (aMap.getMaxZoomLevel() == position.zoom) {
						svc.startSpeaking("地图已经放大到最大");
					}

					if (aMap.getMinZoomLevel() == position.zoom) {
						svc.startSpeaking("地图已经缩小到最小");

					}
				}

				@Override
				public void onCameraChange(CameraPosition arg0) {
					// TODO Auto-generated method stub

				}
			});
		}
		Log.i(TAG, "--" + a + "---" + b);
		mRouteOverLay = new RouteOverLay(aMap, null);
	}

	// 计算驾车路线
	private void calculateDriveRoute(int planType) {
		boolean isSuccess = mAMapNavi.calculateDriveRoute(mStartPoints,
				mEndPoints, null, planType);
		if (!isSuccess) {
			Toast.makeText(getActivity(), "路线计算失败,检查参数情况", 0).show();
		}

	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onResume() {
		getActivity().registerReceiver(gNaviReceiver, makeNewMsgIntentFilter());
		super.onResume();
		mapView.onResume();
		svr = new SpeechVoiceRecognition(getActivity(), null, null);
		svc = SpeechVoiceCompound.getInstance(getActivity(), null, svr);

		String str = getArguments().getString("destination");
		if (str != null) {
			if (packKeyInfo(str)) {
				svc.startSpeaking(Constants.F_C_FOUND_RIGHT_ADDR);
			}
			Log.i(TAG, str + ":str");
		} else {
			Log.i(TAG, "都为空的");
		}
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onPause() {
		super.onPause();
		mapView.onPause();
		getActivity().unregisterReceiver(gNaviReceiver);
		// if (svc != null)
		// svc.destroy();
		// if (svr != null)
		// svc.destroy();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onDestroy() {
		routePlanName = null;
		isOk = false;
		isChooseRoutePlan = false;
		pathAddress = null;
		dis = null;
		time = null;
		geocoderSearch = null;
		mRegeocodeQuery = null;
		if (mRouteOverLay != null) {
			mRouteOverLay.removeFromMap();
			mRouteOverLay.destroy();
		}

		if (mAMapNavi != null) {
			mAMapNavi.removeAMapNaviListener(this);
			mAMapNavi.destroy();
		}
		super.onDestroy();
		mapView.onDestroy();
	}

	/**
	 * 显示进度框
	 */
	private void showProgressDialog() {
		if (progDialog == null)
			progDialog = new ProgressDialog(getActivity());
		progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDialog.setIndeterminate(false);
		progDialog.setCancelable(true);
		progDialog.setMessage("正在搜索:\n" + keyWord);
		progDialog.show();
	}

	/**
	 * 隐藏进度框
	 */
	private void dissmissProgressDialog() {
		if (progDialog != null) {
			progDialog.dismiss();
		}
	}

	/**
	 * 开始进行poi搜索
	 */
	protected boolean doSearchQuery(String address) {
		showProgressDialog();// 显示进度框
		query = new PoiSearch.Query(address, "", "上海");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(10);// 设置每页最多返回多少条poiitem
		query.setPageNum(0);// 设置查第一页

		poiSearch = new PoiSearch(getActivity(), query);
		poiSearch.setOnPoiSearchListener(new OnPoiSearchListener() {

			@Override
			public void onPoiSearched(PoiResult result, int rCode) {
				// TODO Auto-generated method stub
				try {
					dissmissProgressDialog();// 隐藏对话框
					if (rCode == 0) {
						if (result != null && result.getQuery() != null) {// 搜索poi的结果
							if (result.getQuery().equals(query)) {// 是否是同一条
								poiResult = result;
								// 取得搜索到的poiitems有多少页
								List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
								List<SuggestionCity> suggestionCities = poiResult
										.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

								if (poiItems != null && poiItems.size() > 0) {
									double lat = poiItems.get(0)
											.getLatLonPoint().getLatitude();
									double lon = poiItems.get(0)
											.getLatLonPoint().getLongitude();
									end_navi = new NaviLatLng(lat, lon);
									Log.i("mContext", lat + "--" + lon);
									ToastUtil.show(getActivity(), lat + "--"
											+ lon);
									isOk = true;
									mStartPoints.add(start_navi);
									mEndPoints.add(end_navi);
									//
									// aMap.clear();// 清理之前的图标
									// PoiOverlay poiOverlay = new
									// PoiOverlay(aMap,
									// poiItems);
									// poiOverlay.removeFromMap();
									// poiOverlay.addToMap();
									// poiOverlay.zoomToSpan();
								} else if (suggestionCities != null
										&& suggestionCities.size() > 0) {
									showSuggestCity(suggestionCities);
									isOk = true;
								} else {
									ToastUtil.show(getActivity(),
											"对不起，没有搜索到相关数据！");
									Log.i(TAG, "对不起，没有搜索到相关数据！2");
									isOk = false;
								}
							}
							if (isOk == true) {
								// routePlanItemChooseAdapter = new
								// RoutePlanItemChooseAdapter(
								// WordDataSet.routePlansLsts,
								// getActivity());
								// associate_key
								// .setAdapter(routePlanItemChooseAdapter);
								associate_key.setVisibility(View.GONE);
								mapView.setVisibility(View.VISIBLE);
								rl_gnavi.setVisibility(View.GONE);
								gnavi_ll_route_plans
										.setVisibility(View.VISIBLE);// 显示线路信息
								calculateDriveRoute(4);
								routePlanName = "避免拥堵";
								isChooseRoutePlan = true;
							}
						} else {
							ToastUtil.show(getActivity(), "对不起，没有搜索到相关数据！");
							Log.i(TAG, "对不起，没有搜索到相关数据！");
							isOk = false;
						}

					} else if (rCode == 27) {
						ToastUtil.show(getActivity(), "搜索失败,请检查网络连接！");
						Log.i(TAG, "搜索失败,请检查网络连接！");
						isOk = false;
					} else if (rCode == 32) {
						ToastUtil.show(getActivity(), "key验证无效");
						Log.i(TAG, "key验证无效");
						isOk = false;
					} else {
						ToastUtil.show(getActivity(), "未知错误，请稍后重试!错误码为:"
								+ rCode);
						Log.i(TAG, "未知错误，请稍后重试!错误码为:" + rCode);
						isOk = false;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onPoiItemDetailSearched(PoiItemDetail arg0, int arg1) {
				// TODO Auto-generated method stub

			}
		});
		poiSearch.searchPOIAsyn();
		return isOk;
	}

	/*
	 * 装载联想词到adapter中
	 */
	public boolean packKeyInfo(String address) {
		showProgressDialog();// 显示进度框
		String newText = address;
		Inputtips inputTips = new Inputtips(getActivity(),
				new InputtipsListener() {

					@Override
					public void onGetInputtips(List<Tip> tipList, int rCode) {
						if (rCode == 0) {// 正确返回
							if (tipList == null) {
								dissmissProgressDialog();// 隐藏对话框
								return;
							}
							lstAk47 = new ArrayList<AssociateKeyClass>();
							int index = tipList.size();
							if (tipList.size() > 5) {
								index = 5;
							}
							for (int i = 0; i < index; i++) {
								lstAk47.add(new AssociateKeyClass(tipList
										.get(i).getName(), tipList.get(i)
										.getDistrict()));
							}
							Log.i(TAG, lstAk47.size() + "--");
							reTermAdapter = new ReTermAdapter(lstAk47,
									getActivity());
							if (index > 0) {
								associate_key.setVisibility(View.VISIBLE);
								mapView.setVisibility(View.GONE);
							}
							associate_key.setAdapter(reTermAdapter);
							dissmissProgressDialog();// 隐藏对话框
						} else {
							dissmissProgressDialog();// 隐藏对话框
							svc = SpeechVoiceCompound.getInstance(
									getActivity(),
									Constants.F_C_NOT_FOUND_RIGHT_ADDR, svr);

							// 导航目的地输入有误
							return;
						}
					}
				});
		try {
			inputTips.requestInputtips(newText, "上海");// 第一个参数表示提示关键字，第二个参数默认代表全国，也可以为城市区号

		} catch (AMapException e) {
			e.printStackTrace();
		}
		if (lstAk47.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * poi没有搜索到数据，返回一些推荐城市的信息
	 */
	private void showSuggestCity(List<SuggestionCity> cities) {
		String infomation = "推荐城市\n";
		for (int i = 0; i < cities.size(); i++) {
			infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:"
					+ cities.get(i).getCityCode() + "城市编码:"
					+ cities.get(i).getAdCode() + "\n";
		}
		ToastUtil.show(getActivity(), infomation);

	}

	BroadcastReceiver gNaviReceiver = new BroadcastReceiver() {

		@SuppressLint("ResourceAsColor")
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			// 这里捕获异常主要是防止空指针和数组下标越界
			try {
				gson = new Gson();
				final String action = intent.getAction();
				Log.i(TAG, "gNaviReceiver" + action);
				SpeechVoiceData svd;
				VoiceDataClass vdc;
				// 本页导航及公共action指令操作
				if (Constants.MAIN_NAVI_ACTION.equals(action)
						|| Constants.COMMON_UTIL_ACTION.equals(action)) {
					svd = gson.fromJson(intent.getStringExtra(action),
							SpeechVoiceData.class);
					vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);
					if (vdc.getType().equals(Constants.F_R_NAV_GOTO[0])) {
						// 将颜色设置为白色
						gnavi_tv_not_high_speed_plan.setTextColor(getActivity()
								.getResources().getColor(R.color.white));
						gnavi_tv_not_fees_plan.setTextColor(getActivity()
								.getResources().getColor(R.color.white));
						gnavi_tv_not_traffic_plan.setTextColor(getActivity()
								.getResources().getColor(R.color.white));
						// 重新规划的时候路程和时间制空
						gnavi_tv_not_fees_plan_distance_and_time.setText("");
						gnavi_tv_not_traffic_plan_distance_and_time.setText("");
						gnavi_tv_not_high_speed_plan_distance_and_time
								.setText("");
						isChooseRoutePlan = false;
						if (packKeyInfo(vdc.getValue())) {
							svc.startSpeaking(vdc.getPromptKey());
						}
					} else if (vdc.getType().equals(
							Constants.F_R_CHOOSE_ITEM[0])) {
						if (isChooseRoutePlan == false) {// 开始选择路径
							AssociateKeyClass akc = reTermAdapter.lists
									.get(CommonUtil.getIndex(vdc.getValue()));
							if (doSearchQuery(akc.getKeyName())) {
								calculateDriveRoute(4);
							}
						}

					} else if (vdc.getType().equals(
							Constants.F_R_NAVI_ROUTE_PLAN[0])) {
						if (vdc.getValue().equals("避免拥堵")) {
							routePlanName = "避免拥堵";
							// gnavi_ll_not_traffic_plan
							// .setBackgroundColor(R.color.green);
						} else if (vdc.getValue().equals("不走高速")) {
							routePlanName = "不走高速";
							// gnavi_ll_not_high_speed_plan
							// .setBackgroundColor(R.color.green);
						} else if (vdc.getValue().equals("避免收费")) {
							routePlanName = "避免收费";
							// gnavi_ll_not_fees_plan
							// .setBackgroundColor(R.color.green);
						}
						if (routePlanName != null) {
							// 移除之前绘制的路线
							if (mRouteOverLay != null) {
								mRouteOverLay.removeFromMap();
							}
							int index = WordDataSet.routePlans
									.get(routePlanName);
							calculateDriveRoute(index);

						}
					} else if (vdc.getType()
							.equals(Constants.F_R_START_NAVI[0])) {
						Log.i(TAG, "导航开始！");

						if (start_navi != null && end_navi != null) {
							Log.i(TAG, "start_navi != null && end_navi != null");
							int index = 4;// 推荐默认路线：时间最短且避免拥堵
							if (routePlanName != null) {
								index = WordDataSet.routePlans
										.get(routePlanName);
							}
							HudProjectApplication.naviPath = mAMapNavi
									.getNaviPath();
							HudProjectApplication.zoom = aMap
									.getCameraPosition().zoom;
							sni = new StartNaviInfo(start_navi, end_navi, index);
							SpeechVoiceData data = new SpeechVoiceData();
							data.setCommand(Constants.MAIN_HUD_COM);
							data.setValue(gson.toJson(sni));
							CommonUtil.processBroadcast(getActivity(), data);
						}
					}
					// 缩放地图
					else if (vdc.getType().equals(
							Constants.F_R_ENLARGE_OR_NARROW_MAP[0])) {
						// 如果地图显示的话
						if (mapView.getVisibility() == View.VISIBLE) {
							// 放大地图
							if (vdc.getValue().equals(
									Constants.F_R_ENLARGE_OR_NARROW_MAP[1])) {
								CameraUpdate cuIn = CameraUpdateFactory
										.zoomIn();
								aMap.moveCamera(cuIn);
							}
							// 缩小地图
							else if (vdc.getValue().equals(
									Constants.F_R_ENLARGE_OR_NARROW_MAP[2])) {
								CameraUpdate cuOut = CameraUpdateFactory
										.zoomOut();
								aMap.moveCamera(cuOut);
							}
						}
					}
				}
				// 导航界面打电话
				else if (action != null
						&& Constants.MAIN_PHONE_ACTION.equals(action)) {

					svd = gson.fromJson(
							intent.getStringExtra(Constants.MAIN_PHONE_ACTION),
							SpeechVoiceData.class);
					vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);

					svd.setCommand(Constants.MAIN_PHONE_COM);
					svd.setValue(vdc.getValue());
					CommonUtil.processBroadcast(getActivity(), svd);
				}
				// 导航界面显示obd
				else if (action != null
						&& Constants.MAIN_OBD_ACTION.equals(action)) {

					svd = gson.fromJson(
							intent.getStringExtra(Constants.MAIN_OBD_ACTION),
							SpeechVoiceData.class);
					vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);
					svd.setCommand(Constants.MAIN_OBD_COM);
					svd.setValue(vdc.getValue());
					CommonUtil.processBroadcast(getActivity(), svd);
				}
				// 返回首页
				else if (action != null
						&& Constants.MAIN_RETURN_HOME_ACTION.equals(action)) {
					Log.i(TAG, action + "action");
					CommonUtil.retHomeFragment(getActivity());
				}
				// 音乐功能
				else if (action != null
						&& Constants.MAIN_MUSIC_ACTION.equals(action)) {

					svd = gson.fromJson(
							intent.getStringExtra(Constants.MAIN_MUSIC_ACTION),
							SpeechVoiceData.class);
					vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);
					Intent intent2 = new Intent(getActivity(),
							MusicService.class);
					// 停止播放
					if (vdc.getType().equals(Constants.F_R_MUSIC_STOP_PLAY[0])) {
						Log.i("TAG", action + "F_R_MUSIC_STOP_PLAY");
						intent2.putExtra("play", "pause");
						getActivity().startService(intent2);
					}
					// 继续播放
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_CONTINUE_PLAY[0])) {
						intent2.putExtra("play", "playing");
						intent2.putExtra("id", sp.getInt("currentMusic", 0));
						getActivity().startService(intent2);
					}
					// 下一首
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_NEXT_MUSIC_PLAY[0])) {
						intent2.putExtra("play", "next");
						intent2.putExtra("id", sp.getInt("currentMusic", 0) + 1);
						getActivity().startService(intent2);
					}
					// 上一首
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_LAST_MUSIC_PLAY[0])) {
						int index = sp.getInt("currentMusic", 0) - 1;
						if (index < 0) {
							index = 0;
						}
						intent2.putExtra("play", "last");
						intent2.putExtra("id", index);
						getActivity().startService(intent2);
					} else if (vdc.getType().equals(Constants.F_R_MUSIC_ON[0])) {
						svd.setCommand(Constants.MAIN_MUSIC_COM);

						Log.i(TAG, intent
								.getStringExtra(Constants.MAIN_MUSIC_ACTION));
						CommonUtil.processBroadcast(getActivity(), svd);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.i(TAG, "GNaviFragment  出现异常了。。。。。");
			}
		}

	};

	/**
	 * 广播过滤器
	 */
	private static IntentFilter makeNewMsgIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.MAIN_NAVI_ACTION);
		intentFilter.addAction(Constants.MAIN_PHONE_ACTION);
		intentFilter.addAction(Constants.COMMON_UTIL_ACTION);
		intentFilter.addAction(Constants.MAIN_OBD_ACTION);
		intentFilter.addAction(Constants.MAIN_RETURN_HOME_ACTION);
		intentFilter.addAction(Constants.MAIN_MUSIC_ACTION);
		return intentFilter;
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		if (hidden) {
			Log.i(TAG, "GNaviFragment is hidden");
		}
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		progDialog.dismiss();
		super.onDestroyView();
		isChooseRoutePlan = false;
	}

	@Override
	public void onArriveDestination() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onArrivedWayPoint(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteFailure(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteSuccess() {
		// TODO Auto-generated method stub
		AMapNaviPath naviPath = mAMapNavi.getNaviPath();
		if (naviPath == null) {
			return;
		}
		// 获取路径规划线路，显示到地图上
		mRouteOverLay.setRouteInfo(naviPath);
		mRouteOverLay.addToMap();
		mRouteOverLay.zoomToSpan();
		// 途经点
		LatLonPoint mLatLonPoint = new LatLonPoint(naviPath.getCenterForPath()
				.getLatitude(), naviPath.getCenterForPath().getLongitude());
		geocoderSearch = new GeocodeSearch(getActivity());
		// latLonPoint参数表示一个Latlng,第二参数表示范围多少米，GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系
		mRegeocodeQuery = new RegeocodeQuery(mLatLonPoint, 200,
				GeocodeSearch.AMAP);
		geocoderSearch.getFromLocationAsyn(mRegeocodeQuery);
		geocoderSearch.setOnGeocodeSearchListener(this);

		dis = CommonUtil.meterTurnKm(naviPath.getAllLength());
		time = CommonUtil.getTimeFormat(naviPath.getAllTime());
		switch (naviPath.getStrategy()) {
		// 避免拥堵
		case 4:
			// 将选中的字体改为绿色
			gnavi_tv_not_traffic_plan_distance_and_time.setText(dis + "  "
					+ time);
			gnavi_tv_not_traffic_plan.setTextColor(getActivity().getResources()
					.getColor(R.color.green));
			gnavi_tv_not_traffic_plan_distance_and_time
					.setTextColor(getActivity().getResources().getColor(
							R.color.green));
			// 为选择的设置为白色
			gnavi_tv_not_high_speed_plan.setTextColor(getActivity()
					.getResources().getColor(R.color.white));
			gnavi_tv_not_high_speed_plan_distance_and_time
					.setTextColor(getActivity().getResources().getColor(
							R.color.white));

			gnavi_tv_not_fees_plan.setTextColor(getActivity().getResources()
					.getColor(R.color.white));
			gnavi_tv_not_fees_plan_distance_and_time.setTextColor(getActivity()
					.getResources().getColor(R.color.white));
			break;
		// 不走高速
		case 3:
			// 将选中的字体改为绿色
			gnavi_tv_not_high_speed_plan_distance_and_time.setText(dis + "  "
					+ time);

			gnavi_tv_not_high_speed_plan.setTextColor(getActivity()
					.getResources().getColor(R.color.green));
			gnavi_tv_not_high_speed_plan_distance_and_time
					.setTextColor(getActivity().getResources().getColor(
							R.color.green));

			// 为选中的选设置为白色
			gnavi_tv_not_traffic_plan.setTextColor(getActivity().getResources()
					.getColor(R.color.white));
			gnavi_tv_not_traffic_plan_distance_and_time
					.setTextColor(getActivity().getResources().getColor(
							R.color.white));

			gnavi_tv_not_fees_plan.setTextColor(getActivity().getResources()
					.getColor(R.color.white));
			gnavi_tv_not_fees_plan_distance_and_time.setTextColor(getActivity()
					.getResources().getColor(R.color.white));
			break;
		// 避免收费
		case 1:
			// 将选中的字体改为绿色
			gnavi_tv_not_fees_plan_distance_and_time.setText(dis + "  " + time);
			gnavi_tv_not_fees_plan.setTextColor(getActivity().getResources()
					.getColor(R.color.green));
			gnavi_tv_not_fees_plan_distance_and_time.setTextColor(getActivity()
					.getResources().getColor(R.color.green));

			// 为选中的选设置为白色
			gnavi_tv_not_traffic_plan.setTextColor(getActivity().getResources()
					.getColor(R.color.white));
			gnavi_tv_not_traffic_plan_distance_and_time
					.setTextColor(getActivity().getResources().getColor(
							R.color.white));

			gnavi_tv_not_high_speed_plan.setTextColor(getActivity()
					.getResources().getColor(R.color.white));
			gnavi_tv_not_high_speed_plan_distance_and_time
					.setTextColor(getActivity().getResources().getColor(
							R.color.white));
			break;
		default:
			break;
		}
		associate_key.setVisibility(View.GONE);
		mapView.setVisibility(View.VISIBLE);
		rl_gnavi.setVisibility(View.GONE);
		gnavi_ll_route_plans.setVisibility(View.VISIBLE);// 显示线路信息
	}

	@Override
	public void onEndEmulatorNavi() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetNavigationText(int arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGpsOpenStatus(boolean arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviFailure() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChange(AMapNaviLocation arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNaviInfoUpdate(NaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	@Deprecated
	public void onNaviInfoUpdated(AMapNaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForTrafficJam() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForYaw() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartNavi(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTrafficStatusUpdate() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGeocodeSearched(GeocodeResult arg0, int arg1) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onRegeocodeSearched(RegeocodeResult arg0, int arg1) {
		// TODO Auto-generated method stub
		pathAddress = arg0.getRegeocodeAddress().getStreetNumber().getStreet();
		if (pathAddress != null && !pathAddress.equals("")) {
			pathAddress = "主要途径点：" + pathAddress;
		}
		Log.i(TAG, "getCrossroads():" + pathAddress);
		svc.startSpeaking("当前路线," + "全程：" + dis + "," + time + ","
				+ pathAddress);
	}
}
